import { useEffect, useState } from 'react';
import { Form, Input, Modal, message } from 'antd';
import md5 from 'js-md5';
import { getDetail, resetPassword } from '@/request/userMange';
import MyModal from '@/components/modal';

const ResetPassWord = ({ open, actionInfo, handleClose }) => {
  const [form] = Form.useForm();
  const [detail, setDetail] = useState<any>({});
  const [loading, setLoading] = useState(false);

  // 关闭弹框
  const onClose = () => {
    handleClose();
    form.resetFields();
    setDetail({});
  };

  // 提交
  const onSubmit = async () => {
    setLoading(true);
    try {
      const data = await form.validateFields();
      const res = await resetPassword({
        personId: actionInfo?._id,
        password: md5(data.passwordConfirm),
      });
      if (res) {
        message.success('操作成功');
        onClose();
      }
      setLoading(false);
    } catch (err: any) {
      setLoading(false);
      message.warning(err.message);
    }
  };

  // 获取详情
  const getInfo = async () => {
    try {
      const res: any = await getDetail({ personId: actionInfo?._id || '' });
      if (typeof res === 'string') {
        message.warning(res);
      } else {
        setDetail(res);
      }
    } catch (err) {
      console.log(err);
    }
  };

  // 密码校验
  const checkPwd = (value) => {
    if (!value) {
      return Promise.reject();
    }
    if (value.length < 6) {
      return Promise.reject(new Error('密码长度不能小于6位'));
    }
    return Promise.resolve();
  };

  useEffect(() => {
    if (open && actionInfo?._id) {
      getInfo();
    }
  }, [open]);

  return (
    <MyModal
      open={open}
      title="重置密码"
      onCancel={onClose}
      onOk={() => {
        onSubmit();
      }}
      destroyOnClose
      maskClosable={false}
      confirmLoading={loading}
    >
      <Form form={form} colon={false} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} initialValues={{ isDelete: true }}>
        <Form.Item label="用户名">
          <Input disabled placeholder="请输入" allowClear value={detail.userName} />
        </Form.Item>
        <Form.Item label="密码" name="password" rules={[{ required: true, validator: (_, value) => checkPwd(value) }]}>
          <Input.Password placeholder="请输入" allowClear />
        </Form.Item>
        <Form.Item
          label="确认密码"
          name="passwordConfirm"
          style={{ marginBottom: '0' }}
          rules={[
            { required: true, message: '请输入用户名' },
            {
              validator: (_: any, value: any) => {
                const passwordValue = form.getFieldValue('password');
                if (passwordValue && value !== passwordValue) {
                  return Promise.reject(new Error('两次密码不一致'));
                }
                return checkPwd(value);
              },
            },
          ]}
        >
          <Input.Password placeholder="请输入" allowClear />
        </Form.Item>
      </Form>
    </MyModal>
  );
};
export default ResetPassWord;
